// 简单的购物车功能实现
const cart = {
    async addToCart(goodsId, name, price) {
        try {
            const response = await fetch(`${window.contextPath}/shopCartServlet`, {
                method: 'POST',
                headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
                body: `action=add&goodsId=${goodsId}&quantity=1`
            });
            const result = await response.json();
            
            if (result.success) {
                this.updateUI(result.data);
                showModal('success', `已将 ${name} 添加到购物车`);
            } else if (result.message === '请先登录') {
                window.location.href = `${window.contextPath}/toLoginServlet`;
            } else {
                showModal('error', result.message || '添加失败');
            }
        } catch (error) {
            console.error(error);
            showModal('error', '添加失败');
        }
    },

    updateUI(cartData) {
        if (!cartData) return;

        // 更新购物车总数
        const badge = document.getElementById('cart-badge');
        if (badge) {
            const quantity = cartData.reduce((sum, item) => sum + item.quantity, 0);
            badge.textContent = quantity;
            badge.style.display = quantity > 0 ? 'block' : 'none';
        }

        // 更新总价
        const total = document.querySelector('.total span');
        if (total) {
            const totalPrice = cartData.reduce((sum, item) => sum + item.price * item.quantity, 0);
            total.textContent = `¥${totalPrice.toFixed(2)}`;
        }

        // 如果购物车为空，显示空购物车提示
        const cartItems = document.querySelector('.cart-items');
        if (cartItems && cartData.length === 0) {
            cartItems.innerHTML = '<div class="empty-cart">购物车是空的</div>';
        }
    }
};

function updateQuantity(goodsId, change) {
    const quantitySpan = event.target.parentElement.querySelector('span');
    const currentQuantity = parseInt(quantitySpan.textContent);
    const newQuantity = currentQuantity + change;

    if (newQuantity >= 1) {
        fetch(`${window.contextPath}/shopCartServlet`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
            },
            body: `action=update&goodsId=${goodsId}&quantity=${newQuantity}`
        })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    location.reload();
                } else {
                    showModal('error', '更新失败：' + data.message);
                }
            })
            .catch(error => {
                console.error('Error:', error);
                showModal('error', '更新失败，请稍后重试');
            });
    }
}

function removeItem(goodsId) {
    showModal('confirm', '确定要删除这个商品吗？', () => {
        fetch(`${window.contextPath}/shopCartServlet`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
            },
            body: `action=remove&goodsId=${goodsId}`
        })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    location.reload();
                } else {
                    showModal('error', '删除失败：' + data.message);
                }
            })
            .catch(error => {
                console.error('Error:', error);
                showModal('error', '删除失败，请稍后重试');
            });
    });
}

// 初始化购物车数据
document.addEventListener('DOMContentLoaded', () => {
    fetch(`${window.contextPath}/shopCartServlet`)
        .then(response => response.json())
        .then(result => {
            if (result.success) {
                cart.updateUI(result.data);
            }
        })
        .catch(error => {
            console.error('Error:', error);
            showModal('error', '加载购物车失败，请刷新页面重试');
        });
});

// 导出到全局
window.cart = cart;
